package com.ruijie.config;

import java.beans.PropertyVetoException;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.mchange.v2.c3p0.ComboPooledDataSource;

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages ={ "com.ruijie.orm" })
public class PersistenceConfig {
	
//	@Bean
//	public MapperScannerConfigurer getMapperScannerConfigurer(){
//		MapperScannerConfigurer mapperScannerConfigurer = new  MapperScannerConfigurer();
//		mapperScannerConfigurer.setBasePackage("com.ruijie.orm");
//		
//		return mapperScannerConfigurer;
//	}
//	
	
	@Bean(name = "dataSource")
	public DataSource dataSource() {
		ComboPooledDataSource ds = new ComboPooledDataSource();
		ds.setUser("root");
		ds.setPassword("root");
		try {
			ds.setDriverClass("com.mysql.jdbc.Driver");
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
		ds.setJdbcUrl("jdbc:mysql://192.168.54.32:3306/ca?useUnicode=true&amp;characterEncoding=utf-8");
		return ds;
	}

	
	@Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("com.ruijie.orm");
//      ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
//          bean.setMapperLocations(resolver.getResources("classpath:**mapper/*.xml"));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
	
//	@Bean
//    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
//		SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
//		sqlSessionTemplate.close();
//        return sqlSessionTemplate;
//    }
	

	@Bean(name = "transactionManager")
	public PlatformTransactionManager transactionManager(DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

}
